import React, { PureComponent } from 'react';
import { reportError } from '../actions/error';
import {showLoading, hideLoading } from '../restClient/promiseCounter';
import store from 'store';

export default (loader, componentProps) =>
  class AsyncComponent extends PureComponent {
    static Component = null
    state = {
      Component: AsyncComponent.Component,
      isLoading: false,
    }
    componentWillMount() {
      if (!this.state.Component) {
        showLoading();
        loader().then((Component) => {
          AsyncComponent.Component = Component;
          hideLoading();
          this.setState(() => ({
            Component,
          }));
        }).catch((error) => {
          hideLoading();
          store.dispatch(reportError(error));
        });
      }
    }
    render() {
      const { Component } = this.state;
      if (Component) {
        return <Component {...this.props} {...componentProps} />;
      }
      return null;
    }
  };
